package org.example;

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums1 = {100, 4, 200, 1, 3, 2};
        System.out.println("示例 1: " + solution.longestConsecutive(nums1)); // 输出 4

        int[] nums2 = {0, 31, 7, 2, 5, 8, 4, 6, 0, 1};
        System.out.println("示例 2: " + solution.longestConsecutive(nums2)); // 输出 9

        int[] nums3 = {1, 0, 1, 2};
        System.out.println("示例 3: " + solution.longestConsecutive(nums3)); // 输出 3
    }
    static class Solution{
        public int longestConsecutive(int[] nums){
            if (nums == null || nums.length == 0) return 0;
            //用set去重
            Set<Integer> set = new HashSet<>();
            for (int num : nums) {
                set.add(num);
            }
            //将set转换为List并排序
            List<Integer> sortedList = new ArrayList<>(set);
            Collections.sort(sortedList);
            //遍历排序后的List，找到最长的连续序列
            int maxLength = 1;
            int currentLength = 1;
            for(int i = 1;i<sortedList.size();i++){
                if(sortedList.get(i) == sortedList.get(i-1)+1){
                    currentLength++;
                    maxLength = Math.max(maxLength,currentLength);
                }else{
                    currentLength = 1;//重置当前长度
                }
            }
            return maxLength;
        }
    }
}